package dataView

import (
	"context"
	"encoding/json"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/code"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/common"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/client/dataview"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/rpc"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type DataViewListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 列表
func NewDataViewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DataViewListLogic {
	return &DataViewListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DataViewListLogic) DataViewList(req *types.DataViewListReq) (resp *types.DataViewListDataRes, err error) {

	resData := make([]types.DataVIewListItemRes, 0)

	resp = &types.DataViewListDataRes{List: resData}

	if _, ok := common.All[req.ModelType]; !ok {
		return nil, code.ParamsInvalid
	}

	u, err := l.svcCtx.SettingService.DataView.DataViewList(l.ctx, &dataview.DataViewListReq{ModelType: rpc.ModelType(req.ModelType), MerchantId: 1})

	if err != nil {
		logc.Error(l.ctx, "DataViewList err:", err)
		return nil, err
	}

	if u.Code != int64(code.SettingRpcSuccessful.Code()) {
		return nil, code.BusinessFailure
	}

	for _, v := range u.Data.List {
		vs := map[string]interface{}{}

		_ = json.Unmarshal([]byte(v.Value), &vs)
		resData = append(resData, types.DataVIewListItemRes{
			Id:         v.Id,
			MerchantId: v.MerchantId,
			ModelType:  int64(v.ModelType),
			Value:      vs,
			Type:       v.Type,
		})
	}

	resp.List = resData
	return resp, nil
}
